<script lang="ts" setup>
import type { BookAddRequest } from '#/api/types/index.js';

import { ref, watch } from 'vue';

const props = defineProps<{
  initialData: BookAddRequest;
  optionType: string;
}>();
const emit = defineEmits(['update', 'add', 'cancel']);

const formData = ref({ ...props.initialData });
const open = ref(true);
const optionType = ref(props.optionType);
watch(
  () => props.initialData,
  (newData) => {
    formData.value = { ...newData };
  },
  { deep: true, immediate: true },
);

const handleOk = () => {
  if (optionType.value === 'add') {
    emit('add', formData.value);
  } else {
    emit('update', formData.value);
  }
  open.value = false;
};

const handleCancel = () => {
  emit('cancel', false);
};
</script>

<template>
  <a-modal
    v-model:open="open"
    title="新增书籍"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-form :model="formData" layout="vertical">
      <a-form-item
        :rules="[{ required: true, message: '请输入书籍名' }]"
        label="书籍名"
        name="title"
      >
        <a-input v-model:value="formData.title" />
      </a-form-item>
      <a-form-item label="书籍作者" name="author">
        <a-input v-model:value="formData.author" />
      </a-form-item>
      <a-form-item label="出版年份" name="publication_year">
        <a-input v-model:value="formData.publicationYear" />
      </a-form-item>
      <a-form-item label="书籍类型" name="genre">
        <a-input v-model:value="formData.genre" />
      </a-form-item>
      <a-form-item label="书本描述" name="description">
        <a-textarea v-model:value="formData.description" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
/* 样式可以根据需要调整 */
</style>
